import React, {Component} from 'react';
import ButtonConfirmationBox from './ChildrenComponent/ButtonConfirmationBox';
import TimeShow from './ChildrenComponent/TimeShow';
import UpperPartOfTheForm from './ChildrenComponent/UpperPartOfTheForm';
import BottomPartOfTheForm from './ChildrenComponent/BottomPartOfTheForm';
import moment from 'moment';
import $ from 'jquery';
import 'antd/dist/antd.css';
import './ZhongKongSSCXTJLX2.css'


class ZhongKongSSCXTJLX2 extends Component {
    constructor(props) {
        super(props);
        this.state = {
            riqi: moment().format('YYYY-MM-DD'),
            timeChose: 0,//选择的班次 0代表1-7 1代表8-15 2代表16-23
            zhibiao: [null, null, null, null, null, null, null, null, null],//从数据库获取的标准
            time: [],
            formData: [],
            average: [],
            ratio: [],
            passRate: [],
            upperData: [{'shuju': []}, {'shuju': []}, {'shuju': []}, {'shuju': []},
                {'shuju': []}, {'shuju': []}, {'shuju': []}, {'shuju': []},
                {'shuju': []}, {'shuju': []}, {'shuju': []}, {'shuju': []},
                {'shuju': []}, {'shuju': []}, {'shuju': []}, {'shuju': []},
                {'shuju': []}, {'shuju': []}, {'shuju': []}, {'shuju': []},
                {'shuju': []}, {'shuju': []}, {'shuju': []}, {'shuju': []},],
            bottomData: [[[], [], 0, [],], [[], [], 8, [],], [[], [], 16, [],]],//页面下半部分的数据
            person: '',//传入的值班人员
            isEnable: true,//输入框是否可以进行输入
            date: '',
        }
    }

    /**onRef控制子组件提交表单**/
    onRef = (ref) => {
        this.BottomForm = ref;
    };

    //判定是否已登录，是否有权限
    componentWillMount() {
        fetch('/api/ZhongKS/check', {
            method: 'post',
            credentials: 'include',
            headers: {
                'Content-Type': 'application/json',
                'authorization': window.localStorage.authorization,
            }
        })
            .then(res => res.json())
            .then(data => {
                if (data['code'] === 0) {
                }
                else {
                    this.props.history.push('/index');
                }
            })
            .catch(error => console.error('Error:', error))
    }

    componentDidMount() {
        /**首先查询当前页面是否有历史纪录并赋值给upperData**/
        const riqi = this.state.riqi;
        const jsondata = {
            'startRiqi': riqi,
            'startXiaoshi': 0,
            'endRiqi': riqi,
            "endXiaoshi": 23,
            'leixing': 'ZKSX2',
            'zhonglei': 0,
        };
        fetch("/api/ZhongKS/query", {
            method: 'POST',
            credentials: "include",
            body: JSON.stringify(jsondata), // data can be `string` or {object}!
            headers: {
                'Content-Type': 'application/json',
                'authorization': window.localStorage.authorization,
            }
        })
            .then(res => res.json())
            .then(data => {
                if (data['code'] === 0) {//判定是否成功
                    let upperData = this.state.upperData;
                    let bottomData = this.state.bottomData;
                    let buttomdata = bottomData;//将string类型的bottomData转化为json类型
                    for (let i = 0; i < data['data'].length; i++) {
                        if (data['data'][i]['zhonglei'] === 1) {//类型为1是上表数据
                            let shuju = data['data'][i]['shuju'];//取出data中的数据
                            let str = shuju.split(',');//去除数据中的string逗号
                            let a = [];//临时的number数据数组
                            for (let i = 0; i < str.length; i++)//将string转换成number
                                a[i] = parseInt(str[i]);
                            data['data'][i]['shuju'] = a;//数据数组归还给data
                            const xiaoshi = data['data'][i]['xiaoshi'];//按小时排序把数据传给upperdata
                            upperData[xiaoshi] = data['data'][i];
                        }
                        else if (data['data'][i]['zhonglei'] === 2) {//类型为2是下表数据
                            const xiaoshi = data['data'][i]['xiaoshi'];//按小时排序把数据传给upperdata
                            buttomdata[xiaoshi] = eval(data['data'][i]['shuju']);
                        }
                    }
                    console.log(upperData);
                    this.setState({//传值给upperData和bottomData
                        upperData: upperData,
                        bottomData: buttomdata,
                        person: window.localStorage.name,
                    });
                }
            })
            .catch(error => console.error('Error:', error))
            .then(response => console.log('Success:', response));

        /**从服务器获取指标**/
        const leixing = {'leixing': "ZKS"};
        fetch("/api/zhibiao/query", {
            method: 'POST',
            body: JSON.stringify(leixing), // data can be `string` or {object}!
            headers: {
                'Content-Type': 'application/json',
                'authorization': window.localStorage.authorization,
            }
        })
            .then(res => res.json())
            .then(data => {
                    if (data['code'] === 0 && data['zhibiao']['leixing'] === 'KZS') { //判定是否成功
                        let zhi = data['zhibiao']['zhibiao'];//去除指标的逗号
                        const zhibiao = zhi.split(',');
                        let a = [];
                        for (let i = 0; i < zhibiao.length; i++)
                            a[i] = parseFloat(zhibiao[i]);
                        this.setState({
                            zhibiao: a,
                        });
                    }
                }
            )
            .catch(error => console.error('Error:', error))
            .then(response => console.log('Success:', response));
    }


    /**点击提交数据**/
    handleSubmit = () => {
        this.BottomForm.postToHome();
    };

    /**ajax传值结束**/

    /**
     * 响应班次变化
     **/
    handleTimeChose(x) {
        this.setState({
            timeChose: x
        });
    }

    /**传输当前日期到父页面**/
    handleDate(x) {
        this.setState({
            date: x
        });
    }

    /**
     *表单上半部分的数据提交函数
     **/
    handleUpperDataChange(formData, average, ratio, passRate, time) {
        this.setState({
            formData: formData,
            average: average,
            ratio: ratio,
            passRate: passRate,
            time: time,
        });
    }

    /**
     *表单下半部分的数据提交函数
     **/
    handleBottomDataChange(data) {
        this.setState({
            bottomData: data
        })
    }

    returnBack = () => {
        this.props.history.push("/index");
    };

    render() {
        return (
            <div style={{padding: '1%'}}>
                <h1 align="center">福石水泥3000t/d中控室烧成系统运行记录</h1>
                {/*表单最上的时间及人员显示*/}
                <TimeShow person={this.state.person} handleTimeChose={this.handleTimeChose.bind(this)}
                          handleDate={this.handleDate.bind(this)}
                />
                <div
                    style={{
                        border: "1px solid black",
                        margin: "10px 20px 10px 20px"
                    }}
                >
                    {/*表单上半部分*/}
                    <UpperPartOfTheForm
                        riqi={this.state.riqi}
                        standard={this.state.zhibiao}
                        timeChose={this.state.timeChose}
                        person={this.state.person}
                        time={this.state.time}
                        upperData={this.state.upperData}
                        post={this.handleUpperDataChange.bind(this)}/>
                    {/*表单下半部分*/}
                    <BottomPartOfTheForm
                        onRef={this.onRef}
                        riqi={this.state.riqi}
                        timeChose={this.state.timeChose}
                        person={this.state.person}
                        bottomData={this.state.bottomData}
                        post={this.handleBottomDataChange.bind(this)}/>

                </div>
                {/*三个按钮*/}
                {/* <div
                    style={{
                        margin: "0px 0px 20px 50px",
                        display: "inline-block"
                    }}
                >
                    <ButtonConfirmationBox action={this.returnBack.bind(this)} buttonText="返回"/>
                </div> */}
                <div
                    style={{
                        float: "right",
                        margin: "0px 50px 20px 0px",
                        display: "inline-block"
                    }}
                >
                    <ButtonConfirmationBox type="primary" buttonText="提交"
                                           action={this.handleSubmit}
                    />
                </div>
            </div>
        );

    }
}

export default ZhongKongSSCXTJLX2;